const db = require('./db.js');
const http = require('http');
  const formidable = require('formidable');
  const util = require('util');
  const fs = require('fs');
 const path = require('path');
 const mime=require('mime')
 const request=require('request');
 const download=require('download');
 const archiver = require('archiver');
 const AdmZip = require('adm-zip');
const { log } = require('console');
const { type } = require('os');
//   const fstream = require('fstream');
//   const tar = require('tar');
//   const zlib = require('zlib');

 var arr = [];
 var stuhomecr=new Array;

// 用户登录
exports.user_login = (req, res) => {
    console.log();
    let sql = "SELECT * from tb_student where stu_id=? and stu_pwd=?";
    let data = [req.body.user_sno, req.body.user_pwd];
    db.base(sql, data, (result) => {
        //如果学生表查的结果为空,那就去教师表再查一次
        if(result[0]==null){
          sql="SELECT * from tb_teacher where teacher_sno=? and teacher_pwd=?"
          db.base(sql, data, (result) => {
            if(result[0]==null){
                res.send('null')
            }else{
                res.json(result[0]);
            }
          })
        }else{
            res.json(result[0]);
        }
    })
  
}

//学生端初始化
exports.student_getData=(req,res)=>{
    let sql="select * from student_homework where stu_id=?"
    let data=[req.body.studnetID]
    console.log(data);
    db.base(sql,data,(result)=>{
        res.send(result);   
    })
}


//学生端加载作业
exports.student_homework=(req,res)=>{
   let sql="select * from tb_homework where id=?"
   let data=[req.body.homework_id]
   db.base(sql,data,(result)=>{
       res.send(result)
   })
}

//学生端上传作业信息
exports.student_submit=(req,res)=>{
    if(+new Date() > +new Date(req.body.endTime)){
        res.send('超时')
    }else{
        const folder=__dirname+'/public/studentFile/'+req.body.course+'/'+req.body.sClass+'/'+req.body.title+'/'+req.body.stu_id+req.body.stu_name
      //  fs.rmdirSync(folder);
    fs.mkdirSync(folder,{recursive:true},function(err){
        if(err){
            console.log(err);
        }
    })
    let sql="update student_homework set stu_give='已交' where stu_id=? and homework_id=?"
    let data=[req.body.stu_id,req.body.homework_id]
    stuhomecr=[]
     stuhomecr.push(req.body.course)
     stuhomecr.push(req.body.sClass)
     stuhomecr.push(req.body.title)
     stuhomecr.push(req.body.stu_id)
     stuhomecr.push(req.body.homework_id)
     stuhomecr.push(req.body.stu_name)
    db.base(sql,data,(result)=>{
        if (result.affectedRows == 1) {
            res.send("ok");
        }else{
            res.send("error");
        }
    })
   }
}

//学生端上传文件
exports.student_submithomework = (req, res) => {
    const form = new formidable.IncomingForm();
    // 创建学生作业文件夹
    const folder = __dirname + '/public/studentFile/' + stuhomecr[0] + '/' + stuhomecr[1] + '/' + stuhomecr[2] + '/' + stuhomecr[3] + '_' + stuhomecr[5];
    fs.mkdirSync(folder, { recursive: true }, function (err) {
        if (err) {
            console.log(err);
        }
    })
    // 文件上传到的位置
    form.uploadDir = path.join(__dirname, 'public/studentFile/' + stuhomecr[0] + '/' + stuhomecr[1] + '/' + stuhomecr[2] + '/' + stuhomecr[3] + '_' + stuhomecr[5])
    form.keepExtensions = true;
    form.parse(req, (err, fields, files) => {
        // if (err) {
        //     res.status(400);
        // }
        var oldpath;
        var newpath;
        for (var key in files) {
            oldpath = files[key].path;
            // console.log(oldpath);
            newpath = folder + '/' + files[key].name;
            // console.log(newpath);
            fs.rename(oldpath, newpath, function (err) {
                if (err) {
                    console.log("改名失败");
                }
            })
        }
        let sql = "update student_homework set url=? where stu_id=? and homework_id=?"
        // '/studentFile/' + stuhomecr[0] + '/' + stuhomecr[1] + '/' + stuhomecr[2] + '/' + stuhomecr[3] + '_' + stuhomecr[5]
        data = [folder, stuhomecr[3], stuhomecr[4]]
        db.base(sql, data, (result) => { })
        res.end('ok');
    })
}

//老师发布作业信息
exports.teacher_ask = (req, res) => {
    const dir="./public/studentFile/"+req.body.sCourse+'/'+req.body.sClass
    var readDir=fs.readdirSync(dir);
    for(var i in readDir){     
        if(req.body.title==readDir[i]){
            res.send('重复')
            return;
        }
    }
     //创建学生提交作业文件夹
    const folder=__dirname+'/public/studentFile/'+req.body.sCourse+'/'+req.body.sClass+'/'+req.body.title
    fs.mkdirSync(folder,{recursive:true},function(err){
        if(err){
            console.log(err);
        }
    })
     req.body.stu_url='/studentFile/'+req.body.sCourse+'/'+req.body.sClass+'/'+req.body.title
     req.body.state='正常'
     arr.push(req.body);//存数据给文件传输用
    let sql='insert into tb_homework set ?'
    let data=[req.body]
   
    db.base(sql, data, (result) => {
        if (result.affectedRows != 1) {
            console.log("作业表插入失败");
        }

        sql="select max(id) from tb_homework"
        data=[]
    
        db.base(sql,data,(result)=>{
          let maxid=result[0]['max(id)'];
           sql="select stu_id,stu_name from tb_student where stu_class=?"
           data=[req.body.sClass]
    
           db.base(sql,data,(result)=>{
               sql="insert into student_homework set ?"
    
               for(let i in result){
                   data=[];
                  var string={
                    stu_class:req.body.sClass,
                    stu_id:result[i].stu_id,
                    stu_name:result[i].stu_name,
                    course:req.body.sCourse,
                    homework_id:maxid,
                    homework_name:req.body.title,
                    homework_sendTime:req.body.sendTime,
                    homework_endTime:req.body.endTime,
                    stu_give:"未交",
                    state:"正常",
                  }
                   data.push(string);
                   db.base(sql,data,(result)=>{
                  })
               }
               res.json({data:"ok"})
           })
        })
    })
}


//老师发布作业文件
exports.teacher_sendfile =(req,res) =>{
    const form = new formidable.IncomingForm();
    form.uploadDir =path.join(__dirname,'public/teacherFile/'+arr[0].sCourse);
    // 保留上传文件的后缀名字
    form.keepExtensions = true;

    // 解析客户端传递过来的FromData对象
    form.parse(req,(err,fields,files) =>{
        // 获取文件名
        var filename = files.file.name;
        

        // 获取文件路径
        var oldpath = files.file.path;
        var newpath = __dirname+'/public/teacherFile/'+arr[0].sCourse+'/'+files.file.name;
       
       
        fs.rename(oldpath,newpath,function(err){
            if(err){
                console.log("改名失败");
                console.log(err);
            }
        })
    
           sql="update tb_homework set url=? where id in (select id from (select max(id) from tb_homework) e )" 
           data=['/teacherFile/'+arr[0].sCourse+'/'+files.file.name]
           db.base(sql, data, (result) => {
            if (result.affectedRows == 1) {
               res.send('ok')
            }
            else{
               res.send('error')
            }
           })   
    })
}


//老师查看发布作业
exports.teacher_getData=(req,res)=>{
    let sql='select * from tb_homework where teacher_son=?'
    data=[req.body.teacher_son]
    db.base(sql,data,(result)=>{
        res.json(result)
    }) 
}



//教师端统计未交人数
exports.teacher_statistics=(req,res)=>{
    var send=[]
    let sql='select stu_give from student_homework where homework_id=?'

    for(var i in req.body.d.split(',')){
        let data=[req.body.d.split(',')[i]]
        db.base(sql,data,(result)=>{
            var n=0
            for(var j in result){
                  if(result[j].stu_give=='未交'){
                      n++;
                  }
              }
            var m = Number(data)
            send.push({[''+m]:n})
            if(send.length==req.body.d.split(',').length){
               res.send(send)
              }
             
        })
    }
}


//教师端统计未交人数详细信息
exports.teacher_statisticsClass=(req,res)=>{
    let sql="select * from student_homework where homework_id=? and stu_give='未交'"
    let data=[req.body.homework_id]
    db.base(sql,data,(result)=>{
        res.send(result)
    })
}

//老师下载学生文件
exports.teacher_download=(req,res)=>{
    let sql='select stu_url from tb_homework where id=?'
    let data=[req.body.id]
    db.base(sql,data,(result)=>{
        var filePath = './public'+result[0].stu_url //获取文件路径        
         var zipPath = './public'+result[0].stu_url+'.zip';  //压缩包生成路径 
        compress(filePath,zipPath); 
        res.send('http://localhost:3000'+result[0].stu_url+'.zip');
    })
}

//教师端查看班级
exports.teacher_getClassData=(req,res)=>{
    let sql="select * from tb_student where stu_class=(select teacher_class from tb_teacher where teacher_sno=?) and state not in ('删除')"
    let data=[req.body.teacher_son]
    db.base(sql,data,(result)=>{
        res.send(result)
    })
}

//教师端修改班级
exports.teacher_modifyClassData=(req,res)=>{
    // console.log(req.body);
     let s=JSON.stringify(req.body)
       s=JSON.parse(s)
     console.log(s);
     console.log(s['delestudent[0][stu_id]']);
     console.log(s. delestudentLength);
     if(s.delestudentLength!=0){
        for(var i=0;i<s.delestudentLength;i++){
        let sql="update tb_student set state='删除' where stu_id=?"
            console.log(s['delestudent['+i+'][stu_id]']);
            let data=[s['delestudent['+i+'][stu_id]']]
            db.base(sql,data,(result)=>{})
        }
     }
     if(s.modifystudentLength!=0){
        for(var i=0;i<s.modifystudentLength;i++){
            let sql="update tb_student set stu_name=?,stu_sex=?,stu_class=?,stu_pwd=?,role=?,state=? where stu_id=?"
               // console.log(s['delestudent['+i+'][stu_id]']);
                let data=[s['modifystudent['+i+'][stu_name]'],s['modifystudent['+i+'][stu_sex]'],s['modifystudent['+i+'][stu_class]'],
                s['modifystudent['+i+'][stu_pwd]'],s['modifystudent['+i+'][role]'],s['modifystudent['+i+'][state]'],s['modifystudent['+i+'][stu_id]']]
                db.base(sql,data,(result)=>{})
            }
     }
     if(s.addstudentLength!=0){
        for(var i=0;i<s.addstudentLength;i++){
            let sql="insert into tb_student set ?"
              //  console.log(s['delestudent['+i+'][stu_id]']);
                let data=[{
                     stu_id:s['addstudent['+i+'][stu_id]'],
                      stu_name:s['addstudent['+i+'][stu_name]'],
                      stu_sex:s['addstudent['+i+'][stu_sex]'],
                      stu_class:s['addstudent['+i+'][stu_class]'],
                      stu_pwd:s['addstudent['+i+'][stu_pwd]'],
                      role:s['addstudent['+i+'][role]'],
                      state:s['addstudent['+i+'][state]']
                          }]
                db.base(sql,data,(result)=>{})
            }
     }
     res.send('ok')
    // for(var i=0;i<s.deleLength;i++){
    //     let sql="update tb_student set state='删除' where stu_id=?"
    //     console.log(s['dele['+i+'][stu_id]']);
    //     let data=[s['dele['+i+'][stu_id]']]
    //     db.base(sql,data,(result)=>{
    //         if (result.affectedRows == 1) {
    //         res.send('ok')
    //         }
    //     })
    // }
    
}

// 上传班级文件
exports.uploadstu_file = (req, res) => {
    var rs = JSON.stringify(req.body);
    var count = req.body.count;
    rs = JSON.parse(rs)
    console.log('oo');
    var data = [];
    var len = Object.keys(rs);
    console.log(len.length); 
    for (var i = 0; i < (len.length-1)/ count; i++) {
        var value = {
            stu_id: rs['stufile[' + i + '][sno]'],
            stu_name: rs['stufile[' + i + '][uname]'],
            stu_sex: rs['stufile[' + i + '][sex]'],
            stu_class: rs['stufile[' + i + '][sclass]'],
            stu_pwd: rs['stufile[' + i + '][pwd]'],
            role: '学生',
            state: '正常',
        }
        data.push(value);
    }
    let sql = "insert into tb_student set ?";
    for(var i=0;i<data.length;i++){
        db.base(sql, [data[i]], (result) => {
        })
    }
    res.send('ok');
}

//打包
function compress(filePath,zipPath){
    var dirList = fs.readdirSync(filePath); //获取文件列表

    var level = 9;  //压缩等级
   //创建最终打包文件的输出流
    var output = fs.createWriteStream(zipPath);
   //生成archiver对象，打包类型为zip
   var archive = archiver('zip', {
      zlib: {
         level: level
      }
    });
    //功能一
    //对文件进行压缩
    // dirList.forEach(item=>{
    //     archive.append(fs.createReadStream(filePath+item), {'name': item});
    // })
    //对文件夹进行压缩
     archive.directory(filePath, false);
     archive.pipe(output); //将打包对象与输出流关联
    //监听所有archive数据都写完
    output.on('close', function() {
    //console.log('压缩完成', archive.pointer() / 1024 / 1024 + 'M');
    // printData();
    //readZip();
    });
    archive.on('error', function(err) {
    throw err;
    });
    //打包
    archive.finalize();
}

